<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :before-open="beforeOpen"
               v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
               @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
               @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #status="{row}">
        <el-tag v-if="row.status === 1" size="small" type='success'>有效</el-tag>
        <el-tag v-if="row.status === 2" size="small" type="warning">待审核</el-tag>
        <el-tag v-if="row.status === 3" size="small" type="info">失效</el-tag>
      </template>
      <template slot="menuLeft">
        <!--        <el-button type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete">删 除-->
        <!--        </el-button>-->
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出
        </el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button
          type="text"
          size="small"
          icon="el-icon-s-check"
          class="none-border"
          @click.stop="handleEdit(scope.row)"
          v-if="scope.row.status===2"
        >审批
        </el-button>
      </template>
    </avue-crud>
    <!--    <el-dialog title="用户数据导入" append-to-body :visible.sync="excelBox" width="555px">-->
    <!--      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">-->
    <!--        <template slot="excelTemplate">-->
    <!--          <el-button type="primary" @click="handleTemplate">-->
    <!--            点击下载<i class="el-icon-download el-icon&#45;&#45;right"></i>-->
    <!--          </el-button>-->
    <!--        </template>-->
    <!--      </avue-form>-->
    <!--    </el-dialog>-->
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, examine} from "@/api/business/medicine";
import option from "@/const/business/medicine";
import {mapGetters} from "vuex";
import NProgress from "nprogress";
import {exportBlob} from "@/api/common";
import {getToken} from "@/util/auth";
import {downloadXls} from "@/util/util";
import {dateNow} from "@/util/date";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        // columnBtn:false,
        emptyBtn: false,
        columnBtn: false,
        headerAlign: 'center',
        menuWidth: 280,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        viewBtn: true,
        selection: false,
        dialogClickModal: false,
        searchShowBtn: true,
        searchIcon: true,
        labelWidth: 130,
        searchIndex: 3,
        column: [
          {
            label: "药品流水号",
            prop: "medicineNo",
            type: "input",
            search: true,
            searchLabelWidth: 120,
            searchSpan: 6,
            editDisabled: true,
            rules: [{
              required: true,
              message: "请输入",
              trigger: "blur"
            }],
            width: 120,
            overHidden: true,
          },
          {
            label: "通用名",
            prop: "medicineName",
            type: "input",
            search: true,
            searchLabelWidth: 60,
            searchSpan: 6,
            rules: [{
              required: true,
              message: "请输入",
              trigger: "blur"
            }],
            width: 220,
            overHidden: true,
          },
          {
            label: "状态",
            prop: "status",
            type: "select",
            dicData: [{
              label: "待审核",
              value: "2"
            },
              {
                label: "正常",
                value: "1"
              },
              {
                label: "失效",
                value: "3"
              }],
            search: true,
            searchLabelWidth: 100,
            searchSpan: 6,
            formatter: (res) => {
              if (res.status === 1) {
                return "有效"
              } else {
                return "待审核"
              }
            },
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            width: 80,
            fixed: 'right'
          },

          {
            label: "剂型",
            prop: "shotType",
            type: "input",
            search: true,
            searchLabelWidth: 50,
            searchSpan: 6,
            rules: [{
              message: "请输入",
              trigger: "blur"
            }],
            width: 100,
            overHidden: true,
          },
          {
            label: "规格",
            prop: "specification",
            type: "input",
            search: true,
            searchLabelWidth: 100,
            searchSpan: 6,
            rules: [{
              message: "请输入",
              trigger: "blur"
            }],
            width: 100,
            overHidden: true,
          },
          {
            label: "包装",
            prop: "packages",
            type: "input",
            // search: true,
            // searchLabelWidth: 60,
            searchSpan: 6,
            rules: [{
              message: "请输入",
              trigger: "blur"
            }],
            width: 100,
            overHidden: true,
          },
          {
            label: "质量类型",
            prop: "qualityType",
            type: "input",
            width: 100,
            overHidden: true,
          },
          {
            label: "新版基药属性",
            prop: "baseMedProp",
            type: "input",
            width: 100,
            overHidden: true,
          },
          {
            label: "医保编码",
            prop: "insuranceCode",
            type: "input",
            width: 100,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入医保编码",
              trigger: "blur",
            }],
          },
          {
            label: "YPID",
            prop: "drugId",
            type: "input",
            width: 100,
            overHidden: true,
          },
          {
            label: "新版基药编码",
            prop: "baseDrugCode",
            type: "input",
            width: 100,
            overHidden: true,

          },
          {
            label: "采购方式",
            prop: "procurement",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=procurement",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            width: 100,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输采购方式",
              trigger: "blur",
            }],
          },
          {
            label: "带量采购类别",
            prop: "quantityPurchaseCategory",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=quantityPurchaseCategory",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            width: 100,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输带量采购类别",
              trigger: "blur",
            }],
          },

          {
            label: "生产企业注册号",
            prop: "produceCompanyNo",
            type: "input",
            width: 110,
            overHidden: true,
          },
          {
            label: "生产企业名称",
            prop: "produceCompanyName",
            type: "input",
            search: true,
            searchLabelWidth: 100,
            searchSpan: 6,
            rules: [{
              message: "请输入",
              trigger: "blur"
            }],
            width: 220,
            overHidden: true,
          },
          {
            label: "申报企业注册号",
            prop: "declareCompanyNo",
            type: "input",
            //search: true,
            searchLabelWidth: 120,
            searchSpan: 6,
            rules: [{
              message: "请输入",
              trigger: "blur"
            }],
            hide: true,
            width: 110,
            overHidden: true,
          },
          {
            label: "申报企业名称",
            prop: "declareCompanyName",
            type: "input",
            hide: true,
            //search: true,
            searchLabelWidth: 100,
            searchSpan: 6,
            rules: [{
              message: "请输入",
              trigger: "blur"
            }],
            width: 220,
            overHidden: true,
          },
          {
            label: "挂网中标价",
            prop: "bidPrice",
            type: "input",
            viewDisplay: false,
            width: 100,
            overHidden: true,
            rules: [{
              required: true,
              message: "挂网中标价为数字",
              trigger: "blur",
              pattern: /^[0-9]+(\.[0-9]+)?$/,
            }],
          },
          {
            label: "范围",
            prop: "scope",
            type: "input",
            width: 100,
            overHidden: true,
          },
          {
            label: "挂网类型",
            prop: "publishType",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=hang_net_type",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            search: true,
            searchSpan: 6,
            rules: [{
              required: false,
              message: "请选择挂网类型",
              trigger: "blur"
            }],
            width: 180,
            overHidden: true,
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.medicine_add, false),
        viewBtn: this.vaildData(this.permission.medicine_view, false),
        delBtn: this.vaildData(this.permission.medicine_delete, false),
        editBtn: this.vaildData(this.permission.medicine_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    handleEdit(row) {
      this.$confirm("确认审批通过数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return examine(row);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          new Promise((resolve, reject) => {
            remove(row.id).then(res => {
              resolve(res)
            })
          }).then(res => {
            if (res.data.success) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            }
          })
          this.onLoad(this.page);
        })

    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleExport() {
      this.$confirm("是否导出药品数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          const {status, shotType, medicineNo, publishType, medicineName, specification, produceCompanyName} = this.query;
       //   console.log(this.query.medicineNo)
          const params = {
            status,
            shotType,
            medicineNo,
            publishType,
            medicineName,
            specification,
            produceCompanyName
          };

          const queryStr = Object.entries(params)
            .filter(([key, val]) => val !== undefined) // 过滤掉值为 undefined 的条件
            .map(([key, val]) => `${key}=${val}`)
            .join('&');
       // console.log(queryStr)
          const url = `/api/medicine/exportMedicine?${this.website.tokenHeader}=${getToken()}&${queryStr}`;

          NProgress.start();

          exportBlob(url)
            .then(res => {
              downloadXls(res.data, `药品数据表${dateNow()}.xlsx`);
              NProgress.done();
            });

        }
      );
    },
    auditStatusFormate(row) {
      if (row.status) {
        return row.status === '1'
          ? '有效'
          : row.status === '2'
            ? '未审核'
            : ''
      }
    },
  }
};
</script>

<style>
</style>
